--[[  
	main.lua
	file that does basically everything for DKPTracker
	everything needed to run this is already embedded into the 'lib' directory

	Thanks -Ingshtrom
]]--

local raidll = {}
local frame

-- local variables
  -- main window
local context2 = UI.CreateContext('LMVContext') 
context2:SetSecureMode('restricted')


function GetRaid()
        raidll = {}
	local groupCount = LibSRM.GroupCount()
	if groupCount > 0 then
		for i=1,groupCount do
			local unitID,aas = LibSRM.Group.Inspect(i)
			local currentMember = Inspect.Unit.Detail(unitID)
			local sname = ''
			if currentMember~=nil then
				sname=currentMember.name
			end
			print (i..'       '..sname)
			raidll[i]={aas,sname,'','','',{value='.'}}
		end
		for i=groupCount,20 do
		raidll[i]={'','','','','',{value='.'}}
		end

                frame.paneTab2.grid:fill (raidll)
	else
		print("Could not find anyone in your group/raid!")
	end

end

function VersionReqCheck(name, failed, message)
	if not failed then
		print("Version request sent successfully!")
	else
		print("Version request failed for: "..tostring(name))
	end
end


function GetKBMVer()
	for key,value in pairs(raidll) do
        	Command.Message.Send(value[2], "KBMVerReq", "v", function (failed, message) VersionReqCheck(name, failed, message) end)
                value[3]=''
	end

end
function Send1Members()
        -- Inspect.Item.Detail("i0DAC80000C03D4CD").type
        -- Inspect.Item.Detail("I2785E23B232724B7,F838BAA0C938DF8C,,0A1F25CD50418CE7,000000190000001E,,,")
	--Command.Message.Broadcast('raid', nil, "LootVoteReq", "i0DAC800003C2E716:нужно-ненужно", function (failed, message) VersionReqCheck(name, failed, message) end)
	Command.Message.Broadcast('raid', nil, "LootVoteReq", Inspect.Item.Detail("I7A9F27E84309A842,C3F3E7FBAAAE1FB2,,,,,,").type..":нужно-ненужно", function (failed, message) VersionReqCheck(name, failed, message) end)
	--print (Inspect.Item.Detail("i0DAC80000C415AB3").type)
end

function Send2Members(Data)
	Command.Message.Broadcast('raid', nil, "LootVoteInfo", Data, function (failed, message) VersionReqCheck(name, failed, message) end)
end


local strsplit = string.split
tcol={'FF007F','FFFF0F','00FF00'}
function UpdateTable(From,  Data,col)
	for key,value in pairs(raidll) do
    	if value[2]==From then
            if col ~=6 then
    		value[col]={value=Data,color='FFFF0F'}
    	    else --00FF00 green orangered #FF007F
    	      vl=string.sub(Data,1,1)
    		value[col]={value=Data,color=tcol[tonumber(vl)]}

	    end
	end
	end
   	frame.paneTab2.grid:fill (raidll)
end


function DKPPars()
	for key,value in pairs(strsplit(frame.inputVar:getValue(),'\r')) do
        local ss=strsplit(value,'\t')
if #ss==2 then
--print(value)
	for rk,rv in pairs(raidll) do
	--print (rv[2]..'- -'..ss[1])
    	if rv[2]==ss[1] then
	for sk,sv in pairs(ss) do
    		rv[5]=sv
	end
	end
	end
end
end
   	frame.paneTab2.grid:fill (raidll)


end
local myClickFunc2 = function (index)
   local cvote=1
   if raidll[index][6].value ~= '.' then
     cvote=string.sub (raidll[index][6].value,1,1)
   end
   --cvote=cvote-1
   --cvote=cvote+1
   if tonumber(cvote)>1 then
   cvote=cvote-1
   mlabel={'не нужен', 'оффспек',  'майн спек', }
   UpdateTable(raidll[index][2],  cvote..':'..mlabel[cvote],6)

   end
end

local myClickFunc = function (index)
   local cvote=1
   if raidll[index][6].value ~= '.' then
     cvote=string.sub (raidll[index][6].value,1,1)
   end
   cvote=cvote+1
   mlabel={'не нужен', 'оффспек',  'майн спек', }
   UpdateTable(raidll[index][2],  cvote..':'..mlabel[cvote],6)

end

function PMessageHandler(From, Type, Channel, Identifier, Data)
	if Type == "raid" then --and Data ~= nil then
		if Identifier == "LootVoteInfo" then
			print(From.." is vote "..Data)
            UpdateTable(From,  Data,6)
		end
				
	end

	if From ~= KBM.Player.Name and Data ~= nil then
		if Type then
			if Type == "send" then
				if Identifier == "KBMVerInfo" then
                    UpdateTable(From,  Data,3)

				end
			end
		end
	end
end

function loo()
	function UI.Native.Character.Event:Loaded() 
		print('UI.Native.Character.Event:Loaded() ')
	end
	function UI.Native.Loot.Event:Loaded() 
		print('UI.Native.Loot.Event:Loaded() ')
	end
end

 


-- initializing function
----   still need to add events for right/left clicking
function init(addon)
        print(      addon)
	if (addon == 'LootMasterVote') then

	frame = UI.CreateFrame ('nkExtWindow', 'debugFrame', context2, 
				{fontsize = 14, width = 620, height = 600,  visible = false, 
			color = {border = "000000", body = "333333", header = "3B5998", title = "FFFFFF", footer="444444"},
						title = 'Работает только в рейде!!! ', 
				anchors = {{from = "CENTER", object = UIParent, to = "CENTER",x=199,y=0 }}, 
			closeable = true, collapsible = true, dragable = true,
	 })

	frame.paneTab2 = UI.CreateFrame ('nkExtFrame', 'dfTab2', frame:getBody(true), 
			{ color = {body = "444444"}, visible = true,fontsize = 15, width = 600, height = 550,
			anchors = {{from = "TOPLEFT", object = frame:getBody(true), to = "TOPLEFT", x = 10, y = 10}}, })

	frame.paneTab2.grid = nkGenie.ExtGrid:new('nkDebugLogGrid', frame.paneTab2:getElement(), { layer = 1, fontsize = 14, color = { label = 'FFFFFF', border = '000000', body = '333333', bodyhighlight = 'FFFFFF', labelhighlight = '000000'}, 
					anchors = {{ from = 'CENTERLEFT', object = frame.paneTab2:getElement(), to = "CENTERLEFT", x = 10, y = 5}} })
	frame.paneTab2.grid:getElement():SetLayer(1)
			
	frame.paneTab2.grid:layout ({	{align = 'left', header = 'uid', width = 75 }, 
					{align = 'center', header = 'Name', width = 100 }, 
					{align = 'left', header = 'KBM', width = 50},
					{align = 'left', header = 'LMV', width = 50},
					{align = 'left', header = 'DKP', width = 80},
					{align = 'left', header = 'Vote', width = 100},
					}, 20, {})
	frame.paneTab2.grid:setClickEvent (myClickFunc, false)
	frame.paneTab2.grid:setClickEvent (myClickFunc2, true)
	


frame:SetVisible(true)

	frame.bL = UI.CreateFrame('nkExtButton', 'btPrev', frame.paneTab2:getElement(), 
			{ label = 'Raid', color = {body = "3B5998", border="000000", label = "FFFFFF"}, 
		anchors = {{ from = "BOTTOMLEFT", object = frame.paneTab2:getElement(), to = "BOTTOMLEFT", x = 10, y = -10 }},
		func = GetRaid })

	frame.bL2 = UI.CreateFrame('nkExtButton', 'bt2', frame.paneTab2:getElement(), 
			{ label = 'KBM', color = {body = "3B5998", border="000000", label = "FFFFFF"}, 
		anchors = {{ from = "BOTTOMLEFT", object = frame.bL:getElement(), to = "BOTTOMRIGHT", x = 10, y = 0 }},
		func = GetKBMVer })

	frame.bL3 = UI.CreateFrame('nkExtButton', 'bt3', frame.paneTab2:getElement(), 
			{ label = 'Жми меня!!', color = {body = "3B5998", border="000000", label = "FFFFFF"}, 
		anchors = {{ from = "BOTTOMLEFT", object = frame.bL2:getElement(), to = "BOTTOMRIGHT", x = 10, y = 0 }},
		func = Send1Members })

	frame.bL4 = UI.CreateFrame('nkExtButton', 'bt4', frame.paneTab2:getElement(), 
			{ label = 'LMV', color = {body = "3B5998", border="000000", label = "FFFFFF"}, 
		anchors = {{ from = "BOTTOMLEFT", object = frame.bL3:getElement(), to = "BOTTOMRIGHT", x = 10, y = 0 }},
		func = loo })

	frame.bL5 = UI.CreateFrame('nkExtButton', 'bt5', frame.paneTab2:getElement(), 
			{ label = 'DKP', color = {body = "3B5998", border="000000", label = "FFFFFF"}, 
		anchors = {{ from = "BOTTOMLEFT", object = frame.bL4:getElement(), to = "BOTTOMRIGHT", x = 10, y = 0 }},
		func = DKPPars })

	frame.bL6 = UI.CreateFrame('nkExtButton', 'bt5', frame.paneTab2:getElement(), 
			{ label = 'Vote CLEAR', color = {body = "3B5998", border="000000", label = "FFFFFF"}, 
		anchors = {{ from = "BOTTOMLEFT", object = frame.bL5:getElement(), to = "BOTTOMRIGHT", x = 10, y = 0 }},
		func =  function (addon) for i=1,20 do raidll[i][6]={value='.'} end;frame.paneTab2.grid:fill (raidll) end })

	frame.inputVar = UI.CreateFrame('nkExtTextField', 'nkDebufInputVar', 
		frame.paneTab2.grid:getElement(), 
		{value = 'Сюда записать ДКП', width = 500, height = 45, layer = 3, --visible = false,
		color = { body = '444444', border = 'FFFFFF' }, 
		anchors = {{ from = "TOPLEFT", object = frame.paneTab2:getElement(), to = "TOPLEFT", x = 10, y = 10}},})



	
  -- register slash command handler
	-- begin table.insert(...)


	--Command.Message.Accept("raid", "LootVoteReq")
	Command.Message.Accept("raid", "LootVoteInfo")
	function UI.Native.Character.Event:Loaded() 
		print('UI.Native.Character.Event:Loaded() ')
	end
	function UI.Native.Loot.Event:Loaded() 
		print('UI.Native.Loot.Event:Loaded() ')
	end
	nkManager.init('LMV', nil, function() frame:SetVisible(true) end)



end -- end init() 
end -- end init() 



-- get things rollling!
--init()
function runs(args)
      if (args == nil or args == "") and not frame:isVisible() then
        frame:SetVisible(true)
      elseif (args == nil or args == "") and frame:isVisible() then
        print("I am not opening up the window again! It is already visible!!")
      else
        print("The only command available for LMV is /lmv")
      end
    end
table.insert(Command.Slash.Register('lmv'), {runs, "LootMasterVote", 'LMV_OnSlash'})

--function nkWardrobe.main(addon)
table.insert(Event.Addon.Load.End, {init, "LootMasterVote", "addonLoaded"})
table.insert(Event.Message.Receive, {PMessageHandler, "LootMasterVote", "Messenger Handler"})
